package com.soriya.nestlive.im

import android.util.Log
import com.google.gson.GsonBuilder
import com.soriya.nestlive.im.message.IMMessage
import com.soriya.nestlive.im.serializer.MessageTypeDeserializer
import com.soriya.nestlive.im.serializer.MessageTypeSerializer
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class ImHandler @Inject constructor() : ChannelInboundHandlerAdapter() {

    companion object {
        private val messageListenerList: MutableList<(IMMessage) -> Unit> = mutableListOf()
    }

    override fun channelRead(ctx: ChannelHandlerContext?, msg: Any?) {
        Log.i("SoRiya", "收到消息: $msg")
        val imMessage = GsonBuilder()
            .registerTypeAdapter(MessageType::class.java, MessageTypeSerializer())
            .registerTypeAdapter(MessageType::class.java, MessageTypeDeserializer())
            .create()
            .fromJson(msg?.toString(), IMMessage::class.java)

        Log.i("SoRiya", "messageListenerList: ${messageListenerList.size}")
        messageListenerList.forEach { listener ->
            listener(imMessage)
        }
    }

    fun addImListener(listener: (IMMessage) -> Unit) {
        messageListenerList += listener
    }

    fun removeImListener(listener: (IMMessage) -> Unit) {
        messageListenerList.remove(listener)
    }

}